package com.passer.toolbox.common.file.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.List;

public class WriteFileUtils {

    public static void writeFileByString(String filePath, String fileContent) throws IOException {
        try (FileWriter fileWriter = new FileWriter(filePath)) {
            fileWriter.write(fileContent);
        }
    }

    public static void writeFileByStream(InputStream inputStream, File file) {
        int len;
        byte[] bytes = new byte[1024];
        BufferedOutputStream bufferedOutputStream = null;
        try {
            bufferedOutputStream = new BufferedOutputStream(Files.newOutputStream(file.toPath()));

            while ((len = inputStream.read(bytes)) > 0) {
                bufferedOutputStream.write(bytes, 0, len);
            }
        } catch (IOException ioException) {
            throw new RuntimeException(ioException.getMessage());
        } finally {
            try {
                inputStream.close();
            } catch (IOException ignored) {
            }
            if (bufferedOutputStream != null) {
                try {
                    bufferedOutputStream.close();
                } catch (IOException ignored) {
                }
            }
        }
    }

    public static void mergeFile(List<File> chunks, File file) {
        BufferedOutputStream bufferedOutputStream;
        try {
            bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));
        } catch (FileNotFoundException e) {
            throw new RuntimeException("保存文件夹不存在！");
        }
        BufferedInputStream inputStream = null;
        int len;
        try {
            for (File chunk : chunks) {
                inputStream = new BufferedInputStream(Files.newInputStream(chunk.toPath()));
                // 每次读取1M,数组大小不能太大，会内存溢出
                byte[] bt = new byte[1024 * 1024];
                while ((len = inputStream.read(bt)) != -1) {
                    bufferedOutputStream.write(bt, 0, len);
                    bufferedOutputStream.flush();
                }
            }
        } catch (IOException e) {
            file.delete();
            throw new RuntimeException(e.getMessage());
        } finally {
            try {
                bufferedOutputStream.close();
            } catch (IOException ignored) {
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException ignored) {
                }
            }

        }
    }
}
